


import os
import sys
import json
import logging

from model import ManageVehicles
from PSUtils import PSUtils


class PCGVDeathsController():



	lst_vehicleNames = ["lightning","galaxy","liberator","sunderer","flash","vanguard","reaver","prowler","mosquito","magrider","scythe"]
	#tuple to hold the keys to the faction dictionary returned for a vehicle kill
	tup_factNames = ("tr","nc","vs")
	#Database handler
	dbManager = ManageVehicles()
	psUtils = PSUtils()

	def Run(self):

		if self.dbManager.CheckHasEntities() == False:
			lst_dict_initVals = []

			for name in self.lst_vehicleNames:#initialize a db row for each vehicle giving just the name info
				lst_dict_initVals.append({self.dbManager.dict_dbPropIndexes["name"]:name})

			self.dbManager.InitVehicles(lst_dict_initVals)

		self.WriteToStorage(self.ProcessDicts(self.psUtils.CollectOutfitInfoDicts(["character_list",0,"stats"]) ) ) # this is where the magic happens


	def ProcessDicts(self,lst_statsDicts):
		
		return self.ProcessVehicles(lst_statsDicts)

	def ProcessVehicles(self,lst_statsDicts):
		dict_factionKillDict = None
		str_vehicleName = ""
		
		dict_data = {}
		for name in self.lst_vehicleNames:
			dict_data[name] = [name,[0,0,0],0]


		if len(lst_statsDicts)> 0:             
			for fullDict in lst_statsDicts:

				try:
					subDict = fullDict["killed_by"]["vehicle"]
				    

					for vehicleKey in subDict:

						str_vehicleName = subDict[str(vehicleKey)]["name"]
						#logging.info(str_vehicleName)

						dict_factionKillDict = subDict[str(vehicleKey)]["faction"]

						dict_data[str_vehicleName][1] = [sum(pair) for pair in zip(dict_data[str_vehicleName][1], [int(dict_factionKillDict[self.tup_factNames[0]]),
												                                                                   int(dict_factionKillDict[self.tup_factNames[1]]),int(dict_factionKillDict[self.tup_factNames[2] ] ) ] ) ]                                                                                               

						#logging.info(dict_data[str_vehicleName][1])
					
		


				except KeyError:
					logging.info("Oh noes! KeyError")


				finally:
					stuff = "happening"
		for k,list_item in dict_data.iteritems():
			list_item[2] = sum(list_item[1])
		return dict_data
					








	def WriteToStorage(self,dict_data):
		if dict_data!= None:

			lst_dict_updateVals = []
			
			for keyD,list_valueD in dict_data.iteritems():
				lst_dict_updateVals.append( {self.dbManager.dict_dbPropIndexes["name"]:keyD,
			                                 self.dbManager.dict_dbPropIndexes["factionKills"]:list_valueD[1],
			                                 self.dbManager.dict_dbPropIndexes["totalKills"]:list_valueD[2]})
					                           
	
			self.dbManager.UpdateVehicles(lst_dict_updateVals)